package functions.ems_claim;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;

import com.crc.mam.BaseCase;

import coms.Constants;
import coms.TestDateString;
import coms.process.LoginTest;
import frame.HttpHelper;

/**
 * 
 * @author CHENHAILIAN6
 * 发起报账申请--》付款准备--》保证金退款--》其他保证金退款
 */
public class Payment extends BaseCase {
	
	private org.slf4j.Logger logger = LoggerFactory.getLogger(Payment.class);
	String result;
	//ArrayList<JSONObject> allPlanJSONObject = new ArrayList<JSONObject>();
	public ArrayList<JSONObject> getQueryPlanJSONObjects() {
		return queryPlanJSONObjects;
	}


	public void setQueryPlanJSONObjects(ArrayList<JSONObject> queryPlanJSONObjects) {
		this.queryPlanJSONObjects = queryPlanJSONObjects;
	}


	public int getRecordCount() {
		return recordCount;
	}


	public void setRecordCount(int recordCount) {
		this.recordCount = recordCount;
	}

	ArrayList<JSONObject> queryPlanJSONObjects;
	
	
	int recordCount = 0;
	


	
	/**
	 * 查询付款计划行信息
	 * @param ouCode  公司company_code
	 * @param payPlandueDateFrom  2016-03-01
	 * @param payPlandueDateTo
	 */
	public void queryPlanList(Map<Object ,Object> inputParams) {
		logger.info("queryPlanList  --- start ---------------------");

		/**
		 * 获取开始日期的日历字符串
		 */
		
		String currentPage  = (String) inputParams.get("currentPage");
		if(currentPage == null) {
			currentPage = "1";
		}
		int currentPageNum = Integer.valueOf(currentPage);
		
		String pageSize  = (String) inputParams.get("pageSize");
		if(pageSize == null) {
			pageSize = "10";
		}
		int pageSizeNum = Integer.valueOf(pageSize);
		
		String payPlandueDateFrom = (String) inputParams.get("payPlandueDateFrom");
		String startCalendar = "";
		if(payPlandueDateFrom != null) {
			
			String[] date = payPlandueDateFrom.split("-");
			String year = date[0];
			String month = date[1];
			String day = date[2];
			if(month.startsWith("0")) {
				month = month.replaceFirst("0", "");
			}
			if(day.startsWith("0")) {
				day = month.replaceFirst("0", "");
			}
			startCalendar = TestDateString.afterYearDay(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day));			
		}else {
			payPlandueDateFrom = "";
		}
		
		/**
		 * 获取截止日期的日历字符串
		 */
		String payPlandueDateTo = (String) inputParams.get("payPlandueDateTo");
		String endCalendar = "";
		if(payPlandueDateTo !=null) {
			String[] date = payPlandueDateFrom.split("-");
			date = payPlandueDateTo.split("-");
			String year = date[0];
			String month = date[1];
			String day = date[2];
			if(month.startsWith("0")) {
				month = month.replaceFirst("0", "");
			}
			if(day.startsWith("0")) {
				day = month.replaceFirst("0", "");
			}
			endCalendar = TestDateString.afterYearDay(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day));
			
		}else {
			payPlandueDateTo = "";
		}
		String ouCode = (String) inputParams.get("ouCode");
		if(ouCode == null) {
			ouCode = "";
		}
		String invoiceNo = (String) inputParams.get("invoiceNo");
		if(invoiceNo == null) {
			invoiceNo = "";
		}
		String vendorCode = (String) inputParams.get("vendorCode");
		if(vendorCode == null) {
			vendorCode = "";
		}
		String vendorName = (String) inputParams.get("vendorName");
		if(vendorName == null) {
			vendorName = "";
		}
		String queryType = (String) inputParams.get("queryType");
		if(queryType == null) {
			queryType = "";
		}
		String glDateStart = "";
		String glDateEnd = "";	
		String glDateFrom = (String) inputParams.get("glDateFrom");
		if(glDateFrom == null) {
			glDateFrom = "";
		}else {
			glDateStart = TestDateString.getcalendarSingleString(glDateFrom);
		}
		String glDateTo = (String) inputParams.get("glDateTo");
		if(glDateTo == null) {
			glDateTo = "";
		}else {
			glDateEnd = TestDateString.getcalendarSingleString(glDateTo);
		}
		String invoiceDateFrom = (String) inputParams.get("invoiceDateFrom");
		String invoiceStart = "";
		String invoiceEnd = "";		
		if(invoiceDateFrom == null) {
			invoiceDateFrom = "";
		}else {
			invoiceStart = TestDateString.getcalendarSingleString(invoiceDateFrom);
		}
		String invoiceDateTo = (String)inputParams.get("invoiceDateTo");
		if(invoiceDateTo == null) {
			invoiceDateTo = "";
		}else {
			invoiceEnd = TestDateString.getcalendarSingleString(invoiceDateTo);
		}
		String projectCode = (String)inputParams.get("projectCode");
		if(projectCode == null) {
			projectCode = "";
		}
		String projectName = (String)inputParams.get("projectName");
		if(projectName == null) {
			projectName = "";
		}
		String createdPayRequest = (String)inputParams.get("createdPayRequest");
		if(createdPayRequest == null) {
			createdPayRequest = "";
		}
		String currency = (String)inputParams.get("currency");
		if(currency == null) {
			currency = "";
		}
		String requestPaymentTypeName = (String)inputParams.get("requestPaymentTypeName");
		if(requestPaymentTypeName == null) {
			requestPaymentTypeName = "";
		}
		String categoryCode = (String)inputParams.get("categoryCode");
		if(categoryCode == null) {
			categoryCode = "";
		}
			
		String params = "{\"page\":{\"currentPage\":"+currentPageNum+",\"pageSize\":"+pageSizeNum+",\"recordCount\":0},"
				+ "\"params\":{\"ouCode\":\""+ouCode+"\",\"payType\":\"\","
				+ "\"payPlandueDate\":[\""+startCalendar+"T16:00:00.000Z\",\""+endCalendar+"T16:00:00.000Z\"],\"payPlandueDateFrom\":\""+payPlandueDateFrom+"\",\"payPlandueDateTo\":\""+payPlandueDateTo+"\","
				+ "\"vendorName\":\""+vendorName+"\",\"queryType\":\""+queryType+"\",\"glDateFrom\":\""+glDateFrom+"\",\"glDateTo\":\""+glDateTo+"\",\"invoiceNo\":\""+invoiceNo+"\",\"vendorCode\":\""+vendorCode+"\","
				+ "\"invoiceDateFrom\":\""+invoiceDateFrom+"\",\"invoiceDateTo\":\""+invoiceDateTo+"\","
				+ "\"projectCode\":\""+projectCode+"\",\"projectName\":\""+projectName+"\",\"currency\":\""+currency+"\",\"createdPayRequest\":\""+createdPayRequest+"\","
					+ "\"requestPaymentTypeName\":\""+requestPaymentTypeName+"\",\"categoryCode\":\""+categoryCode+"\",\"glDate\":[\""+glDateStart+"\",\""+glDateEnd+"\"],"
				+ "\"invoiceDate\":[\""+invoiceStart+"\",\""+invoiceEnd+"\"]},"
					+ "\"sortDTO\":{\"fieldName\":\"\",\"orderBy\":\"\"}}";
		logger.info(" params : " + params);
		String url = Constants.QUERY_PAY_PLAN_URL;
			try {
				result = HttpHelper.post(params, url);
				logger.info("queryPlanList----" + result);
				status = HttpHelper.isOk;
				logger.info(" isPassed: " + status);
				try {
					JSONObject object = new JSONObject(result);
					int total = object.getInt("total");
					if(total > 0) {
						queryPlanJSONObjects = new ArrayList<JSONObject>();
						recordCount = total;
						JSONArray array = object.getJSONArray("list");
						
						for(int i=0;i<array.length();i++) {
							JSONObject data = array.getJSONObject(i);
							queryPlanJSONObjects.add(data);
							
						//	allPlanJSONObject.add(data);
							logger.info(data.toString());
						}
					}
				}catch(Exception e) {
					
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			logger.info("queryPlanList  --- end ---------------------");
	}
	
	public static void main(String[] args) {
		
	}
	
	/**
	 * 查询付款申请行 的"转账付款信息"/"票据付款信息"/"其他付款信息"
	 * @param inputParam
	 * 必传 ：payRequestLineId payWay
	 */
	public JSONObject queryPayInfo(HashMap<Object,Object> inputParam) {
	  resultJSONObject = null;
	  logger.info("queryPayInfo  --- start ---------------------");

		String payRequestLineId = "";
		String payWay = "";
		payRequestLineId = (String) inputParam.get("payRequestLineId");
		payWay = (String) inputParam.get("payWay");
		if(payRequestLineId == null || payRequestLineId.equals("")) {
			try {
				throw new Exception("payRequestLineId 无值，不能查询");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		String url = Constants.QUERY_PAY_INFO_URL + "/"+payRequestLineId+"/"+payWay;
		try {
			result = HttpHelper.post("", url);
			logger.info("queryPayInfo----" + result);
			status = HttpHelper.isOk;
			logger.info(" isPassed: " + status);
			try {
				resultJSONObject = new JSONObject(result);
				
			}catch(Exception e) {
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("queryPayInfo  --- end ---------------------");	
		return resultJSONObject;
	}
	
	/**
	 * 保存付款信息
	 * 传值 ： payRequestLineIds === 1,2,3,4
	 */
	public void savePayInfo(HashMap<Object,Object> inputMap) {
	  resultJSONObject = null;
      logger.info("savePayInfo  --- start ---------------------");
	  String amount = "";
	  String payWay = "";
	  String paymentMode = "";
	  String payRequestLineIds = "";
	  String ouCode = "";
	  String ouName = "";
	  String accountName = "";
	  String accountNo = "";
	  String configFileCode = "";
	  String payTp = "";
	  String tpCode = "";
	  String settleType = "";
	  String remittanceSpeed = "";
	  String transfersType = "";
	  String fundPlan = "";
	  String summary = "";
	  String purpose = "";
	  if(inputMap != null) {
	    amount =  (String) inputMap.get("amount");
	    if(amount == null) {
	      amount = "";
	    }
	    
	    payWay =  (String) inputMap.get("payWay");
        if(payWay == null) {
          payWay = "";
        }
        
        paymentMode =  (String) inputMap.get("paymentMode");
        if(paymentMode == null) {
          paymentMode = "";
        }
        
        payRequestLineIds =  (String) inputMap.get("payRequestLineIds");
        if(payRequestLineIds == null) {
          payRequestLineIds = "";
        }
        ouCode =  (String) inputMap.get("ouCode");
        if(ouCode == null) {
          ouCode = "";
        }
        ouName =  (String) inputMap.get("ouName");
        if(ouName == null) {
          ouName = "";
        }
        accountName =  (String) inputMap.get("accountName");
        if(accountName == null) {
          accountName = "";
        }
        accountNo =  (String) inputMap.get("accountNo");
        if(accountNo == null) {
          accountNo = "";
        }
        configFileCode =  (String) inputMap.get("configFileCode");
        if(configFileCode == null) {
          configFileCode = "";
        }
        payTp =  (String) inputMap.get("payTp");
        if(payTp == null) {
          payTp = "";
        }
        tpCode =  (String) inputMap.get("tpCode");
        if(tpCode == null) {
          tpCode = "";
        }
        settleType =  (String) inputMap.get("settleType");
        if(settleType == null) {
          settleType = "";
        }
        remittanceSpeed =  (String) inputMap.get("remittanceSpeed");
        if(remittanceSpeed == null) {
          remittanceSpeed = "";
        }
        transfersType =  (String) inputMap.get("transfersType");
        if(transfersType == null) {
          transfersType = "";
        }
        fundPlan =  (String) inputMap.get("fundPlan");
        if(fundPlan == null) {
          fundPlan = "";
        }
        summary =  (String) inputMap.get("summary");
        if(summary == null) {
          summary = "";
        }
        purpose =  (String) inputMap.get("purpose");
        if(purpose == null) {
          purpose = "";
        }
	  }
	  
	  String param = "{\"amount\":\""+amount+"\",\"payWay\":\""+payWay+"\",\"paymentMode\":\""+paymentMode+"\","
	      + "\"payRequestLineIds\":["+payRequestLineIds+"],\"ouCode\":\""+ouCode+"\",\"ouName\":\""+ouName+"\","
	      + "\"accountName\":\""+accountName+"\",\"accountNo\":\""+accountNo+"\",\"configFileCode\":"+configFileCode+","
	      + "\"payTp\":"+payTp+",\"tpCode\":"+tpCode+",\"settleType\":"+settleType+",\"remittanceSpeed\":"+remittanceSpeed+","
	      + "\"transfersType\":"+transfersType+",\"fundPlan\":"+fundPlan+",\"summary\":\""+summary+"\",\"purpose\":\""+purpose+"\"}";
	String url = Constants.SAVE_PAY_INFO_URL;
	logger.info("savePayInfo params---- " + param);
	try {
      result = HttpHelper.post(param, url);
      logger.info("savePayInfo----" + result);
      status = HttpHelper.isOk;
      logger.info(" isPassed: " + status);
      try {
         if(result.trim().equals("UPDATE_SUCCESS")) {
           
         }else {
           status = false;
           throw new Exception ("savePayInfo failed");
         }
          
      }catch(Exception e) {
          
      }
  } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }
  logger.info("savePayInfo  --- end ---------------------"); 
 
}
	
	/**
	 * 返回可以创建的付款计划行信息
	 * @return
	 */
	public JSONObject getVisibelPlan(Map<Object,Object> inputMap) {
	  JSONObject object  = null;
	  boolean isVisible = false;
	 // inputMap.put("currentPage", "1");
	 // inputMap.put("pageSize", "10");
	  queryPlanList(inputMap);
	    int pageSize = 0;
       if(recordCount >0) {
            int mode = recordCount % 10;
            pageSize = recordCount / 10;
            if(mode >0) {
                pageSize  = pageSize +1;
            }
            for(int j=1;j<pageSize+1;j++) {
              logger.info("page :" + String.valueOf(j));
              inputMap.put("currentPage",String.valueOf(j) );
              //inputMap.put("pageSize", "10");
              queryPlanList(inputMap);
              if(queryPlanJSONObjects.size()>0) {
                for(int i=0;i<queryPlanJSONObjects.size();i++) {
                  JSONObject requestLine = queryPlanJSONObjects.get(i);
                  logger.info(requestLine.toString());
                  String createdPayRequest = requestLine.getString("createdPayRequest");
                 logger.info("createdPayRequest : " + createdPayRequest);
                  if(createdPayRequest.equals("N")) {
                    object = requestLine;
                    if(object.getFloat("invoiceAmount")>0) {
                      isVisible = true;
                      break;
                    }
                  }
                }
                if(isVisible) {
                  break;
                }
              }else {
                logger.info("没有付款计划行");
              }
            }
            
        }
	  
	  if(!isVisible) {
	    logger.error("所有的付款计划行都已经被创建了付款申请报账单");
	  }
	  return object;
	}
}
